package com.sckj.springbootdome.controller;

import com.sckj.springbootdome.entity.User;
import com.sckj.springbootdome.sevice.UserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@Slf4j
public class UserController {
    @Resource
    private UserService userService;

    //查询全部
    @RequestMapping(value = "/list")
    public String userList(Model model){
        List<User> users = userService.findAll();
        model.addAttribute("users",users);
        return "index";
    }

    //新增数据
    @RequestMapping("/add")
    public String save(User user){
        userService.save(user);
        return "redirect:/list";
    }
    @RequestMapping("/useradd")
    public String add(){
        return "add";
    }

    //删除数据
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable Integer id, HttpServletResponse servletResponse) throws IOException{
        int count = userService.delete(id);
        if (count == 1){
            servletResponse.sendRedirect("/list");
        }
        return "error";
    }

    //根据id查找
    @RequestMapping(value = "/finduser",method = RequestMethod.POST)
    public String updatePage(@RequestParam(name = "id") int id, Model model){
        User users = userService.get(id);
        model.addAttribute("users",users);
        return "modifie";
    }

    //根据id查找
    @GetMapping("/updatePage/{id}")
    public String updatePage(Model model,@PathVariable int id){
        User users = userService.get(id);
        model.addAttribute("users",users);
        return "modifie";
    }

    @PostMapping("/update")
    public String updateUser(User user){
        userService.update(user);
        return "redirect:/list";
    }


}
